<template>
  <view class="page-container">
    <uni-swiper-dot :info="recipeDetails.instruction" :current="swiperIndex">
      <swiper
        class="swiper"
        @change="handleSwiperChange"
        :style="{ height: swiperHeight + 'px' }"
      >
        <swiper-item v-for="(item, i) in recipeDetails.instruction" :key="item">
          <view :id="'content-wrap' + i" class="swiper-content">
            <view class="img-wrap">
              <image
                class="img"
                mode="heightFix"
                :src="item.url"
                @click="handlePreviewImage(item.url)"
              ></image>
            </view>
            <view class="swiper-step">{{ item.step }}：</view>
            <view class="swiper-text">{{ item.text }}</view>
          </view>
        </swiper-item>
      </swiper>
    </uni-swiper-dot>
    <view class="tips" v-if="recipeDetails.tips"
      >提示：{{ recipeDetails.tips }}</view
    >
    <view class="difficulty" v-if="recipeDetails.difficulty"
      >难度：{{ recipeDetails.difficulty }}</view
    >
    <view class="duration" v-if="recipeDetails.duration"
      >烹饪时间：{{ recipeDetails.duration }}</view
    >
    <view class="ingredient">菜品成分：</view>
    <view v-for="(item, i) in recipeDetails.ingredient" :key="item" class="li"
      >{{ i + 1 }}. {{ item.name }}：{{ item.amount }}</view
    >
    <u-toast ref="uToastRef"></u-toast>
  </view>
</template>

<script setup>
import { onLoad, onShow } from '@dcloudio/uni-app'
import { nextTick } from 'vue'

const loading = ref(false)
const app_id = 'jnfmrsexjrieuwtc'
const app_secret = 'MW0xODl1NHI4NkxBUHd2Qkt2SmRQQT09'
const swiperIndex = ref(0)
const swiperHeight = ref(0)
const recipeDetails = ref({})
const uToastRef = ref(null)

onLoad(options => {
  // console.log(options)
  if (options && Object.keys(options).length) {
    uni.setNavigationBarTitle({
      title: options.name
    })
    initData(options.id)
  }
})

async function initData(id) {
  loading.value = true
  recipeDetails.value = await getRecipeClassList(
    apiModules.home.apiGetRecipeDetails,
    id
  )
  console.log('recipeDetails', recipeDetails.value)
  loading.value = false
  // 动态设置swiper的高度
  nextTick(() => {
    setSwiperHeight()
  })
}

// 动态设置swiper的高度
function setSwiperHeight() {
  let element = '#content-wrap' + swiperIndex.value
  // let query = uni.createSelectorQuery().in(this) // 不清楚不能加in(this)
  let query = uni.createSelectorQuery()
  query.select(element).boundingClientRect()
  query.exec(res => {
    if (res && res[0]) {
      swiperHeight.value = res[0].height
    }
  })
}

function getRecipeClassList(url, id = '-1') {
  return new Promise((resolve, reject) => {
    uni.request({
      url,
      data: {
        id,
        app_id,
        app_secret
      },
      method: 'GET',
      success({ data }) {
        if (data.code === 1 && data.data) {
          console.log('success', data.data)
          resolve(data.data)
        } else {
          uToastRef.value.show({
            type: 'error',
            message: data.msg,
            iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/error.png'
          })
          setTimeout(_ => {
            uni.navigateBack()
          }, 1000)
        }
      },
      fail(err) {
        // console.log('error', err)
        resolve([])
        if (err.errMsg.indexOf('request:fail') > -1) {
          uToastRef.value.show({
            type: 'error',
            message: '请求失败，请检查接口是否可用！',
            iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/error.png'
          })
        }
      }
    })
  })
}

function handleSwiperChange(e) {
  swiperIndex.value = e.detail.current
  setSwiperHeight()
}
function handlePreviewImage(url) {
  // const urls = instruction.map(item => item.url)
  uni.previewImage({
    current: 0,
    urls: [url],
    loop: true,
    longPressActions: true
  })
}
</script>

<style lang="scss">
.page-container {
  padding-bottom: 40rpx;
}
.swiper {
  height: 1100rpx;

  .swiper-content {
    padding-bottom: 40rpx;
    .img-wrap {
      display: flex;
      justify-content: center;
      .img {
        display: block;
        width: 100%;
        height: 860rpx;
      }
    }
    .swiper-step {
      margin-top: 40rpx;
      padding: 0 20rpx;
      font-size: 28rpx;
      font-weight: 600;
    }
    .swiper-text {
      padding: 0 20rpx;
      font-size: 32rpx;
      text-indent: 2em;
    }
  }
}
.tips {
  line-height: 38rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  color: #333;
}
.difficulty {
  line-height: 44rpx;
  padding: 0 20rpx;
  font-size: 32rpx;
  color: #333;
}
.duration {
  line-height: 44rpx;
  padding: 0 20rpx;
  font-size: 32rpx;
  color: #333;
}
.ingredient {
  line-height: 44rpx;
  margin-top: 20rpx;
  padding: 0 20rpx;
  font-size: 32rpx;
  font-weight: 600;
}
.li {
  line-height: 44rpx;
  font-size: 32rpx;
  text-indent: 2em;
  color: #333;
}
</style>
